import dotenv from 'dotenv';

import { install } from 'source-map-support';
install();

import { program } from 'commander';
import { Finder } from "./core/Finder.js";
import { CmdOption } from './typings';

import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { toolchain } from './toolchain.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const myPackage = await fs.readJSON(path.join(__dirname, '../package.json'));

const rmQuotes = (val: string): string => {
    let rst = val.match(/(['"])(.+)\1/);
    if(rst) return rst[2];

    return val;
}

program
	.version(myPackage.version, "-v, --version")
	.option("-n, --project-name <string>", "project name.", rmQuotes)
	.option("-p, --project-root [string]", "project path.", rmQuotes)
	.option("--designer-root <string>", "designer path.", rmQuotes)
	.option("--svr-root <string>", "svr path.", rmQuotes)
	.option("-a, --action <string>", "execute action.", rmQuotes)
	.option("-o, --output [string]", "output file.", rmQuotes)
	.option("--min-size [string]", "specified min size when fixing NPOT.", rmQuotes)
	.option("--min-wh [int]", "specified min width/height when fixing NPOT.", rmQuotes)
	.option("--delete-instruction [string]", "instruction file used for dedupImage action.", rmQuotes)
	.option("-i --input [string]", "input parameter.", rmQuotes)
	.option("-t --target [string]", "target parameter.", rmQuotes)
	.option("--mv-sub-dirs", "move sub dirs.")
    .parse(process.argv);

let opts = program.opts() as CmdOption;
// 使用.env设置项目路径
if (opts.projectName) {
	let envOutput = dotenv.config();
	if(envOutput.error) {
		console.error('env configuration read error: ' + envOutput.error);
		process.exit(1);
	}
	const localProjectRoot = process.env[opts.projectName.toUpperCase()];
	if (localProjectRoot) {
		if (fs.existsSync(localProjectRoot)) {
			console.log('use local project root:', localProjectRoot);
			opts.projectRoot = localProjectRoot;
		} else {
			console.error('local project root not exists:', localProjectRoot)
			process.exit(1);
		}
	}
}
console.log(`cmd options: ${JSON.stringify(opts)}`);
toolchain.opts = opts;

const finder = new Finder();
await finder.execute();
